package com.db.jdbc.pool;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 使用druid连接池数据库连接工具类
 *
 * @author xin.ding
 * @date 2019/12/20 17:26
 */
public class JdbcUtils {

    private static final String DEFAULT_VALIDATION_QUERY = "select 1 from dual";
    private static final int DEFAULT_POOL_SIZE = 1;
    private static final int DEFAULT_POOL_MAX_SIZE = 2;

    private JdbcUtils() {
        throw new IllegalAccessError();
    }

    public static DruidDataSource getDruidDataSource(String driver, String user, String password, String url
            , int poolSize, int poolMaxSize, String validationQuery) {
        DruidDataSource connPool = new DruidDataSource();
        connPool.setDriverClassName(driver);
        connPool.setUsername(user);
        connPool.setPassword(password);
        connPool.setUrl(url);

        // 初始化大小、最小、最大
        connPool.setInitialSize(poolSize);
        connPool.setMinIdle(1);
        connPool.setMaxActive(poolMaxSize);
        // 连接泄漏监测
        connPool.setRemoveAbandoned(true);
        connPool.setRemoveAbandonedTimeout(30);
        connPool.setLogAbandoned(true);
        // 连接等待超时的时间
        connPool.setMaxWait(20000);
        // 检测需要关闭的空闲连接，单位是毫秒
        connPool.setTimeBetweenEvictionRunsMillis(20000);
        // 防止过期
        connPool.setValidationQuery(validationQuery);
        connPool.setTestWhileIdle(true);
        connPool.setTestOnBorrow(true);

        return connPool;
    }

    public static DruidDataSource getDruidDataSource(String driver, String user, String password, String url) {
        return getDruidDataSource(driver, user, password, url, DEFAULT_POOL_SIZE, DEFAULT_POOL_MAX_SIZE, DEFAULT_VALIDATION_QUERY);
    }

    public static DruidDataSource getDruidDataSource(String driver, String user, String password, String url
            , int poolSize, int poolMaxSize) {
        return getDruidDataSource(driver, user, password, url, poolSize, poolMaxSize, DEFAULT_VALIDATION_QUERY);
    }

}
